<?php
define(ERR_LOGFILE, 'ERROR: Cannot open logfile. (maybe \'chmod 777 tmp\' ?)');
define(ERR_DB, 'ERROR: Cannot open database connection. (check your configs)');
define(ERR_DBQUERY, 'ERROR: Cannot query database. (check your configs)');
define(ERR_GOOGLE, 'ERROR: Awh shucks, I searched and searched but found nothing. If you know you should have found somthing you may be blacklisted (lasts about 3-4 hrs).');
if(isset($_REQUEST['page'])) $prepage = $_REQUEST['page'];
else $prepage = 1;
if(isset($_REQUEST['num'])) $prenum = $_REQUEST['num'];
else $prenum = 1;
require_once 'config.php';
require_once 'snarf.lib.php';
$snarf = new snarfer;
#cache results
$statuslog = 'tmp/status.dat';
#
$dbh = mysql_connect($mysqldb['host'], $mysqldb['user'], $mysqldb['pass']);
if(!$dbh) die(ERR_DB);
mysql_select_db($mysqldb['db'], $dbh);
if($_GET['action'] == 'export') {
	$sql='select * from signmeup;';
	$rsSearchResults = mysql_query($sql, $dbh) or die(mysql_error());
	$out = '';
	$fields = mysql_list_fields($mysqldb['db'],'signmeup',$dbh);
	$columns = mysql_num_fields($fields);
	// Put the name of all fields
	for ($i = 0; $i < $columns; $i++) {
		$l=mysql_field_name($fields, $i);
		$out .= '"'.$l.'",';
	}
	$out .="\n";
	 
	// Add all values in the table
	while ($l = mysql_fetch_array($rsSearchResults)) {
		for ($i = 0; $i < $columns; $i++) {
			$out .='"'.$l["$i"].'",';
		}
		$out .="\n";
	}
	// Output to browser with appropriate mime type, you choose ;)
	header("Content-type: text/x-csv");
	//header("Content-type: text/csv");
	//header("Content-type: application/csv");
	header("Content-Disposition: attachment; filename=search_results.csv");
	echo $out;
	exit;
}
if(!isset($_REQUEST['run'])) {
	echo "<h3>Here are your configs:</h3><br>";
	echo "<b>MySQL Config:</b><br><ul>";
	foreach($mysqldb as $name => $value) {
		echo "<li><b>$name</b>: $value";
	}
	echo "</ul>";

	echo "<b>Google Search config:</b><br><ul>";
	foreach($query as $name => $value) {
		echo "<li><b>$name</b>: $value";
	}
	echo "</ul>";
	echo '<br><a href="?run=yes">Click here to RUN</a>';
	echo '<br><a href="capcha.php">Click here to run the CAPTCAs</a>';
	echo '<br><a href="?action=export">Export Results to CSV</a>';
	exit;
}

$sh = fopen($statuslog, 'w+') or die(ERR_LOGFILE);
$suc=0;
$total=0;
$catyou=0;
for($page = $prepage; $page <= $maxpage; $page++) {
	$data = $snarf->GetGoogleResults($query['term'],$page,$maxnum);
	if(!$data) die(ERR_GOOGLE);
	$num=0;
	foreach($data as $key => $target) {
		$num++;
		//if($num == $prenum) next;
		$url = $target['Url'];
		//preg_match('(?:http://)?([^/]', $url, $matches);
		preg_match('/[^.]+\.[^.]+\/+/', $url, $matches);
		if(preg_match('/http/', $matches[0]))
			$url = "{$matches[0]}".$query['signup'];
		else $url = "http://{$matches[0]}".$query['signup'];
		if(preg_match('/http/', $matches[0]))
			$host = "{$matches[0]}".$query['signup'];
		else $host = "http://{$matches[0]}".$query['signup'];
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $query['post']);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$regpage = curl_exec($ch);
		curl_close($ch);
		$status = "$num-$page";
		ftruncate($sh,0);
		fwrite($sh,$status);
	//	echo $regpage;
	//	exit;

		// we get domain name
		$urlh=parse_url($url);
		$urlh=$urlh['host'];

		if(preg_match('/'.$query['succ'].'/i', $regpage)) {
			//echo "SUCC: ".$target['Url'].'<br>';
			// no duplicate domains
			if(!mysql_num_rows(mysql_query("SELECT url FROM `signmeup` WHERE LOCATE('//{$urlh}/',url) LIMIT 1"))){
				$sql = sprintf("INSERT INTO signmeup(url,user,pass,googlerank) VALUES('%s', '%s', '%s', '%s');", $host, $user, $pass, $target['Rank']);
				mysql_query($sql, $dbh) || die(ERR_DBQUERY);
				$suc++;
			}
		} else if(preg_match('/Invalid Code Entered/i', $regpage)) {
			// no duplicate domains
			if(!mysql_num_rows(mysql_query("SELECT url FROM `capcha` WHERE LOCATE('//{$urlh}/',url) LIMIT 1"))){
				$sql = sprintf("INSERT INTO capcha(url,user,pass,post,host,googlerank) VALUES('%s', '%s', '%s', '%s', '%s', '%s');", $host, $user, $pass, $query['post'], $host, $target['Rank']);
				$catyou++;
				mysql_query($sql, $dbh) || die(ERR_DBQUERY.mysql_error());
			}
		} else { //DEBUGecho "FAIL: ".$target['Url'].'<br>';
		}
		$total++;
	}
	sleep(45);
}
echo "DONE!<br>Total: $total<br>Success: $suc<br>CAPTCHA: $catyou";
fclose($sh);
mysql_close($dbh);
//echo $snarf->get_page_rank($_GET['url']);

?>
